package com.duolebo.uteped_sdk.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.duolebo.uteped_sdk.remind.CallRemind;

/**
 * @Author: LiuYang
 * @Date: 2023/12/24 20:56
 * @Description:
 */
public class CallReceiver extends BroadcastReceiver {
    public final String TAG = "CallReceiver";

    private final static String CALL_OUT = "android.intent.action.NEW_OUTGOING_CALL";
    private final static String EXTRA_PHONE_NUMBER = "android.intent.extra.PHONE_NUMBER";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Bundle bundle = intent.getExtras();
        if (bundle == null || action == null)
            return;

        String savedNumber = "";
        if (action.equals(CALL_OUT)) {
            savedNumber = bundle.getString(CallReceiver.EXTRA_PHONE_NUMBER);
            CallRemind.shareInstance().setSavedNumber(savedNumber);
        }
        else {
            String stateStr = bundle.getString(TelephonyManager.EXTRA_STATE);
            String number = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
            savedNumber = number;
            CallRemind.shareInstance().setSavedNumber(savedNumber);
            Log.d(TAG, "phone number：" + savedNumber);
            int state = 0;

            if (TelephonyManager.EXTRA_STATE_IDLE.equals(stateStr)) {
                state = TelephonyManager.CALL_STATE_IDLE;
            } else if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(stateStr)) {
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            } else if (TelephonyManager.EXTRA_STATE_RINGING.equals(stateStr)) {
                state = TelephonyManager.CALL_STATE_RINGING;
            }

            CallRemind.shareInstance().onCallStateChanged(context, state, number);
        }
    }

}
